<?php
// +----------------------------------------------------------------------
// | YFCMF [ WE CAN DO IT MORE SIMPLE]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2020 http://yfcmf.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: rainfer <rainfer520@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\controller\system;

use UploadUtil;
use app\admin\model\setting\Attachment as AttachmentModel;

/**
 * 上传
 * @author rainfer520@qq.com
 */
class Upload extends \think\Controller
{
    public function initialize()
    {
        //跨域访问
        if (config('app_debug') == true) {
            header("Access-Control-Allow-Origin:*");
            // 响应类型
            header("Access-Control-Allow-Methods:GET,POST");
            // 响应头设置
            header("Access-Control-Allow-Headers:x-requested-with,content-type,x-access-token,x-access-appid");
        }
    }

    /**
     * 上传图片
     *
     * @route('upload/upImage')
     */
    public function upImage()
    {
        $filename = input('filename', '', 'trim');
        if (empty($filename)) {
            ajax_return_error('参数错误');
        }
        $res = UploadUtil::upImage($filename);
        $url = request()->domain() . $res['url'];
        ajax_return_ok(['url' => $url,'name'=>$res['name']]);
    }

    /**
     * 上传文件
     *
     * @route('upload/upFile')
     */
    public function upFile()
    {
        $filename = input('filename', '', 'trim');
        if (empty($filename)) {
            ajax_return_error('参数错误');
        }
        $res = UploadUtil::upFile($filename);
        $url = request()->domain() . $res['url'];
        ajax_return_ok(['url' => $url, 'name'=>$res['name']]);
    }

    /**
     * 根据md5检测文件是否存在
     *
     * @route('upload/check')
     */
    public function check()
    {
        $md5 = input('md5', '', 'trim');
        if (empty($md5)) {
            ajax_return_error('md5无效');
        } else {
            $res = AttachmentModel::check($md5);
            ajax_return_ok(['url' => $res['url'] ? (request()->domain() . $res['url']) : '']);
        }
    }
}
